package com.generalaj.io.util;

import java.io.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * A Util class for IO.
 * */
public class IOUtil {

    private static Log LOG = LogFactory.getLog(IOUtil.class);

    public static void close(Closeable reader) {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                LOG.warn(e);
            }
        }
    }
    /**
     * Check file is file. Note: not a dir.
     *
     * @throws RuntimeException if it is not file.
     * */
    public static void checkIsFile(File file) {
        if (file.isDirectory()) {
            LOG.error("File is not file. File name = " + file.getAbsolutePath());
            throw new RuntimeException(file.getAbsolutePath());
        }
    }

    /**
     * Check file is dir. Note: not a file.
     *
     * @throws RuntimeException if it is not dir.
     * */
    public static void checkIsDir(File file) {
        if (file.isFile()) {
            LOG.error("File is not dir. File name = " + file.getAbsolutePath());
            throw new RuntimeException(file.getAbsolutePath());
        }
    }

    /**
     * try to create new file if file doesn't exist.
     */
    public static void createNewFileIfNotExist(String filePath) {
        File file = new File(filePath);
        createNewFileIfNotExist(file);
    }

    /**
     * try to create new file if file doesn't exist.
     */
    public static void createNewFileIfNotExist(File file) {
        if (file == null) {
            throw new NullPointerException();
        }

        // Fix the p. So the file can get its parent file.
        file = new File(file.getAbsolutePath());

        checkIsFile(file);

        LOG.debug("create New File If Not Exist. File = "
                + file.getAbsolutePath());

        if (!file.exists()) {
            try {
                File parentDir = file.getParentFile();

                createNewDirIfNotExist(parentDir);

                if (!file.createNewFile()) {
                    throw new RuntimeException("bad luck.");
                }

            } catch (IOException e) {
                LOG.error("create file fail.", e);
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * try to create new dir if not exist.
     * */
    public static void createNewDirIfNotExist(File dir) {

        if (dir == null) {
            throw new NullPointerException();
        }

        checkIsDir(dir);

        if (!dir.exists()) {
            // Fix the p. So the file can get its parent file.
            dir = new File(dir.getAbsolutePath());

            File parentDir = dir.getParentFile();

            createNewDirIfNotExist(parentDir);

            if (!dir.mkdir()) {
                throw new RuntimeException("bad luck.");
            }
        }
    }

    public static void copyTxtFile(File sourcefile, File targetFile) throws IOException {
        FileCharsetDetector det=new FileCharsetDetector();
        String encoding=det.getFileEncodeing(sourcefile);
        byte[] bytes=FileReadUtil.readBytes(sourcefile);
        String outputString=new String(bytes,encoding);
        FileWriteUtil.save2File(targetFile,outputString.getBytes());
    }

    public static void copyTxtDirectory(File sourceDir, File targetDir) throws IOException{
        File[] file=sourceDir.listFiles();
        if(!targetDir.getCanonicalFile().exists()){
            targetDir.getCanonicalFile().mkdirs();
        }
        for (int i = 0; i < file.length; i++) {
            if(file[i].isFile()){
                File sourceFile=file[i];
                File targetFile=new File(targetDir.getCanonicalFile(),file[i].getName());
                targetFile.createNewFile();
                copyTxtFile(sourceFile, targetFile);
            }else if(file[i].isDirectory()){
                copyTxtDirectory(new File(sourceDir,file[i].getName()),new File(targetDir,file[i].getName()));
            }
        }

    }


    public static void main(String[] args) throws Exception {
        FileCharsetDetector det=new FileCharsetDetector();
        String cs1=det.getFileEncodeing(new File("ademo.txt"));
        System.out.println(cs1);
        byte[] bytes=FileReadUtil.readBytes(new File("ademo.txt"));
        System.out.println(new String(bytes,cs1));
        String charset=det.getFileEncodeing(new File("insert_dm_fcar_f_core_performance.sql"));
        System.out.println(charset);
        bytes=FileReadUtil.readBytes(new File("insert_dm_fcar_f_core_performance.sql"));
        System.out.println(new String(bytes,charset));
    }
}
